/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年7月12日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.filter.smarthome.route;

import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.web.util.UrlPathHelper;

import com.jimi.gateway.utils.Constants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @FileName H5StaticResourceFilter.java
 * @Description: SmartHome h5页面静态资源路径跳转，仿PreDecorationFilter过滤器编写
 *
 * @Date 2017年7月12日 下午4:01:42
 * @author li.shangzhi
 * @version 1.0
 */
public class H5StaticResourceFilter extends ZuulFilter {

	public static final int FILTER_ORDER = 0;

	private final Logger logger = LoggerFactory.getLogger(H5StaticResourceFilter.class);

	private UrlPathHelper urlPathHelper = new UrlPathHelper();

	public H5StaticResourceFilter(ZuulProperties properties) {
		this.urlPathHelper.setRemoveSemicolonContent(properties.isRemoveSemicolonContent());
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		String routeId = String.valueOf(ctx.get("proxy"));
		return Constants.H5_STATIC_RESOURCE_NAMESPACE.equals(routeId);
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		final String requestURI = this.urlPathHelper.getPathWithinApplication(ctx.getRequest());
		logger.info("请求的的客户信息为：{}", ctx.get("zuulRequestHeaders"));
		logger.info("请求的环境为：{}", ctx.get("proxy"));
		String oldUrl = ctx.getRouteHost().toString();
		String newUrl = oldUrl + requestURI;
		ctx.put("requestURI", ""); // 置为空
		ctx.setRouteHost(getUrl(newUrl)); // 将请求重新指定
		logger.info("将请求路由映射到{}", newUrl);
		return null;
	}

	@Override
	public String filterType() {
		return Constants.ROUTE_FILTER;
	}

	@Override
	public int filterOrder() {
		return FILTER_ORDER;
	}

	private URL getUrl(String target) {
		try {
			return new URL(target);
		} catch (MalformedURLException ex) {
			throw new IllegalStateException("Target URL is malformed", ex);
		}
	}
}
